package com.bd.framework.utils.database;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 
 * Description:数据库工厂类
 * createDate：2013-10-14
 * author：刘洋15
 * 
 * @version 1.0
 */
public class ConnectionFactory {
	private static Statement stmt;
	/**
	 * pos数据库连接池
	 */
	public static DBConnectionManager posdb_PoolDataSource;
	/**
	 * 测试数据库连接池，暂时也使用pos库，执行另外操作
	 */
	public static DBConnectionManager basedb_PoolDataSource;
	private ConnectionFactory(){
		
	}
	/**
	 * 获取数据库连接 没有连接池管理
	 * @return
	 */
	public static synchronized Connection getConnectionBASEDB(){
		Connection connection = null;
		try {if(posdb_PoolDataSource==null)
			posdb_PoolDataSource=DBConnectionManager.getInstance();
			connection = posdb_PoolDataSource.getConnection("base");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	/**
	 * 获取数据库连接 没有连接池管理
	 * @return
	 */
	public static synchronized Connection getConnectionPOSDB(){
		Connection connection = null;
		try {if(posdb_PoolDataSource==null)
			posdb_PoolDataSource=DBConnectionManager.getInstance();
			connection = posdb_PoolDataSource.getConnection("pos");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
    /**  
     * 释放连接 freeConnection  
     *   
     * @param conn  
     */  
	public static void freeConnection(Connection conn){
		try {
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/*
	 * 执行一句查询的sql
	 */
	public static ResultSet executeQuery(String sql) throws Exception {
		try {
			//利用Statement对象执行参数的sql
			ResultSet result = stmt.executeQuery(sql);
			return result;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	//执行单句INSERT、UPDATE 或 DELETE 语句, 如果执行INSERT时, 返回主键
	public static int executeUpdate(String sql) throws Exception {
		int result = -1;
		try {
			//执行SQL语句
			stmt.executeUpdate(sql);
			//获得主键
			ResultSet rs = stmt.getGeneratedKeys();
			while(rs.next()) {
				//返回最后一个主键
				result = rs.getInt(1);
			}
			rs.close();
			return result;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
}
